package org.example.ims.Controller.Order;

import org.example.ims.DTO.Response;
import org.example.ims.Entity.Order.OutStockDetail;
import org.example.ims.Service.Order.OutStockDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.NoSuchElementException;

@RestController
@RequestMapping("/outStockDetails")
public class OutStockDetailController {

    private final OutStockDetailService detailService;

    @Autowired
    public OutStockDetailController(OutStockDetailService detailService) {
        this.detailService = detailService;
    }

    @PostMapping
    public ResponseEntity<OutStockDetail> createDetail(@RequestBody OutStockDetail detail) {
        OutStockDetail createdDetail = detailService.createDetail(detail);
        return ResponseEntity.ok(createdDetail);
    }


    @PutMapping("/{detailId}")
    public ResponseEntity<OutStockDetail> updateDetail(
            @PathVariable Integer detailId,
            @RequestBody OutStockDetail detail) {
        OutStockDetail updatedDetail = detailService.updateDetail(detailId, detail);
        return ResponseEntity.ok(updatedDetail);
    }

    @DeleteMapping("/{detailId}")
    public ResponseEntity<Void> deleteDetail(@PathVariable Integer detailId) {
        detailService.deleteDetail(detailId);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{detailId}")
    public ResponseEntity<Response<OutStockDetail>> getDetailById(@PathVariable Integer detailId) {
        try {
            OutStockDetail detail = detailService.getDetailById(detailId);
            return ResponseEntity.ok(Response.success(detail));
        } catch (NoSuchElementException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(Response.<OutStockDetail>error("NOT_FOUND", "OutStockDetail with id " + detailId + " not found"));
        }
    }

    @GetMapping("/search")
    public Response<Page<OutStockDetail>> getAllDetails(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        return Response.success(detailService.getAllDetails(page, size));
    }

    @GetMapping
    public Response<Page<OutStockDetail>> searchDetails(
            @RequestParam(required = false) Integer orderId,
            @RequestParam(required = false) Integer productId,
            @RequestParam(required = false) Integer warehouseId,
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        return Response.success(detailService.searchDetails(orderId, productId, warehouseId, page, size));
    }
}